#include "CloudiskServer.h"
#include "CryptoUtil.h"
#include "workflow/MySQLResult.h"
#include "nlohmann/json.hpp"
#include "wfrest/PathUtil.h"
#include "HashUtil.h"
#include "ParseUtil.h"
#include <map>
#include <string>
#include <sstream>
#include <fstream>
using namespace wfrest;
using namespace protocol;
using std::cout;
using std::endl;
using std::map;
using std::string;
using std::istringstream;
using std::ifstream;
using std::ostringstream;

//获取用户名下的文件列表
void CloudiskServer::register_file_list_modules(){
    m_server.POST("/file/query",[](const HttpReq *req,HttpResp *resp){
        if(req->content_type()!=APPLICATION_URLENCODED){
            resp->set_status(HttpStatusBadRequest);
            return;
        }

        string url;
        req->get_request_uri(url);
        map<string,string> params = ParseUtil::get_query_param(url);
        string token = params["token"];

        ParseUtil::verify_token(req, resp, [req,resp,token](User user){
            if(user.id != 0 && CryptoUtil::verify_token(token,user)){
                const void *body;
                size_t size;
                req->get_parsed_body(&body,&size);
                string body_str = static_cast<const char*>(body);
                string limit_str = (body_str.substr(body_str.find("=")+1)).c_str();
                int limit = std::stoi(limit_str);
                
                //获取用户名下的文件列表并回传给客户端
                string sql_query = "select * from tbl_file where uid = '" + std::to_string(user.id) + "';";
                resp->set_status(HttpStatusOK);
                resp->MySQL(mysql_url,sql_query,[resp,&limit](MySQLResultCursor *cursor){
                    if(cursor->get_cursor_status()==MYSQL_STATUS_GET_RESULT && cursor->get_rows_count()>0){
                        map<string,MySQLCell> record;
                        nlohmann::json retArr = nlohmann::json::array();
                        while(cursor->fetch_row(record) && limit>0){
                            nlohmann::json retMsg;
                            retMsg["FileName"]=record["filename"].as_string();
                            retMsg["FileHash"]=record["hashcode"].as_string();
                            retMsg["FileSize"]=record["size"].as_ulonglong();
                            retMsg["UploadAt"]=record["created_at"].as_datetime();
                            retMsg["LastUpdated"]=record["last_update"].as_datetime();
                            retArr.push_back(retMsg);
                            --limit;
                        }
                        resp->String(retArr.dump());
                    }else{
                        //sql语句执行成功但无结果集，返回204响应码
                        resp->set_status(HttpStatusNoContent);
                    }
                });
            } else {
                resp->set_status(HttpStatusUnauthorized);
            }
        }); 

    });
}